class ChatApplication {
    constructor() {
        this.wsClient = null;
        this.messageManager = new MessageManager();
        this.uiController = new ChatUIController();
        this.currentUser = null;
        this.currentConversation = null;
        
        this.init();
    }
    
    async init() {
        await this.loadUserData();
        this.initWebSocket();
        this.renderConversationList();
        this.setupGlobalHandlers();
    }
    
    // 加载用户数据
    async loadUserData() {
        try {
            const userData = localStorage.getItem('currentUser');
            if (userData) {
                this.currentUser = JSON.parse(userData);
            } else {
                // 如果没有用户数据，创建临时用户
                this.currentUser = await this.createTemporaryUser();
            }
        } catch (error) {
            console.error('加载用户数据失败:', error);
        }
    }
    
    // 初始化WebSocket连接
    initWebSocket() {
        this.wsClient = new WebSocketClient({
            serverUrl: 'ws://localhost:8080/ws',
            onMessage: (data) => this.handleWebSocketMessage(data),
            onConnected: () => this.handleWebSocketConnected(),
            onDisconnected: () => this.handleWebSocketDisconnected()
        });
        
        // 注册消息处理器
        this.wsClient.registerHandler('new_message', (data) => 
            this.handleNewMessage(data));
        this.wsClient.registerHandler('message_recall', (data) => 
            this.handleMessageRecall(data));
    }
    
    // 发送消息
    async sendMessage(content, messageType = 'text', options = {}) {
        if (!this.wsClient || !this.wsClient.isConnected()) {
            this.showNotification('连接未就绪，请检查网络', 'error');
            return false;
        }
        
        const messageData = {
            type: 'new_message',
            conversationId: this.currentConversation?.id,
            senderId: this.currentUser.id,
            content: content,
            messageType: messageType,
            timestamp: new Date().toISOString(),
            clientMessageId: this.generateClientMessageId(),
            ...options
        };
        
        try {
            // 先显示发送中的消息
            this.uiController.displayMessage({
                ...messageData,
                status: 'sending',
                isOwn: true
            });
            
            // 发送到服务器
            await this.wsClient.send(messageData);
            
            return true;
        } catch (error) {
            console.error('发送消息失败:', error);
            this.uiController.updateMessageStatus(
                messageData.clientMessageId, 
                'failed'
            );
            return false;
        }
    }
    
    // 撤回消息
    async recallMessage(messageId) {
        if (!this.currentConversation) return false;
        
        const recallData = {
            type: 'recall_message',
            messageId: messageId,
            conversationId: this.currentConversation.id,
            userId: this.currentUser.id,
            timestamp: new Date().toISOString()
        };
        
        try {
            await this.wsClient.send(recallData);
            return true;
        } catch (error) {
            console.error('撤回消息失败:', error);
            return false;
        }
    }
    
    // 处理新消息
    handleNewMessage(messageData) {
        const isOwnMessage = messageData.senderId === this.currentUser.id;
        
        if (!isOwnMessage) {
            this.playMessageSound();
            this.updateUnreadCount(messageData.conversationId);
        }
        
        this.uiController.displayMessage({
            ...messageData,
            isOwn: isOwnMessage
        });
        
        // 如果当前正在查看这个会话，标记为已读
        if (this.currentConversation?.id === messageData.conversationId) {
            this.markMessagesAsRead(messageData.conversationId);
        }
    }
    
    // 处理消息撤回
    handleMessageRecall(recallData) {
        const success = this.messageManager.recallMessage(
            recallData.conversationId,
            recallData.messageId,
            recallData.recalledBy
        );
        
        if (success) {
            this.uiController.updateMessageDisplay(
                recallData.conversationId,
                recallData.messageId,
                '该消息已被撤回'
            );
        }
    }
}